package A1_哈希表;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LC_18四数之和 {
    public static void main(String[] args){
        int[] nums={1,0,-1,0,-2,2};
        int target=0;
        //List<List<Integer>> res=fourSum(nums,target);
        System.out.println(fourSum(nums,target));
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result=new ArrayList<>();
        Arrays.sort(nums);
        for(int k=0;k<nums.length;k++){
            if(nums[k]>0 && target>0 && nums[k]>target )
                break;//剪枝
            if(k>0 && nums[k]==nums[k-1])
                continue;//去重
            for(int i=k+1;i<nums.length;i++){
                if( nums[i]+nums[k]>target && nums[i]+nums[k]>0 )//target>0
                    break;//二层剪枝
                if(i>k+1 && nums[i]==nums[i-1])
                    continue;//二层去重
                int left=i+1;
                int right=nums.length-1;
                while(right>left){
                    if(nums[k]+nums[i]+nums[left]+nums[right]>target)
                        right--;
                    else if(nums[k]+nums[i]+nums[left]+nums[right]<target)
                        left++;
                    else{
                        result.add(Arrays.asList(nums[k],nums[i],nums[left],nums[right]));
                        while(right>left && nums[left]==nums[left+1])
                            left++;
                        while(right>left && nums[right]==nums[right-1])
                            right--;
                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }
}
